//
//  MXHomeMailFreeVC.m
//  MXの衣柜
//
//  Created by 马霄 on 15/8/11.
//  Copyright (c) 2015年 霄 马. All rights reserved.
// 免邮页
#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)

#import "MXHomeMailFreeVC.h"
#import "AFNetworkHandler.h"
#import "MXHomeMailFreeModel.h"
#import "MXHomeContentCollectionViewCell.h"
#import "MXHomeMailFreeItemDetailVC.h"
#import "MBProgressHUD.h"
@interface MXHomeMailFreeVC ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, retain) NSMutableArray *nineArray;

@property (nonatomic, retain) NSMutableArray *nineTeenArray;

@property (nonatomic, retain) NSMutableArray *twentynineArray;

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) UISegmentedControl *segmentControl;

@property (nonatomic, retain) MBProgressHUD  *HUD;

@property (nonatomic, retain) UIView *alterView;
@end

@implementation MXHomeMailFreeVC
- (void)dealloc
{
    [_HUD release];
    [_alterView release];
    [_segmentControl release];
    [_collectionView release];
    [_nineArray release];
    [_nineTeenArray release];
    [_twentynineArray release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //隐藏导航栏
    self.navigationController.navigationBar.hidden = YES;
    
    
    //全局数组初始化
    self.nineArray = [NSMutableArray array];
    self.nineTeenArray = [NSMutableArray array];
    self.twentynineArray = [NSMutableArray array];
    
    
    //创建一个View
    UIView *titleView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, HEIGHTPRO * 64)] autorelease];
    titleView.userInteractionEnabled = YES;
    titleView.backgroundColor = [UIColor redColor];
    [self.view addSubview:titleView];
    
    
    UIButton *backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backButton.frame = CGRectMake(WIDTHPRO * 10,HEIGHTPRO * 29,WIDTHPRO * 30,HEIGHTPRO * 30);
    [backButton setBackgroundImage:[UIImage imageNamed:@"backButton_blue"] forState:(UIControlStateNormal)];
    [backButton addTarget:self action:@selector(backAction) forControlEvents:(UIControlEventTouchUpInside)];
    [titleView addSubview:backButton];

    
    //设置UISegmentedControl
    NSArray *typeArr = @[@"9块9", @"19块9", @"29块9"];
    self.segmentControl = [[[UISegmentedControl alloc] initWithItems:typeArr] autorelease];
    CGFloat segmentX = WIDTHPRO * 50;
    CGFloat segmentY = HEIGHTPRO * 25;
    CGFloat segmentW = WIDTH -  WIDTHPRO * 2 * (segmentX + WIDTHPRO * 10);
    CGFloat segmentH = HEIGHTPRO * 35;
    self.segmentControl.frame = CGRectMake(segmentX, segmentY, segmentW, segmentH);
    self.segmentControl.alpha = 1;
    self.segmentControl.tintColor = [UIColor whiteColor];
    self.segmentControl.layer.masksToBounds = YES;
    [self.segmentControl addTarget:self action:@selector(segClick:) forControlEvents:(UIControlEventValueChanged)];
    self.segmentControl.selectedSegmentIndex = 0;
    //    segmentControl.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
    self.segmentControl.backgroundColor = [UIColor colorWithRed:179 / 255.0 green:36 / 255.0 blue:37 / 255.0 alpha:1];
    [self.view addSubview:self.segmentControl];
    
    
    [self creatCollectionView];
    [self GetnineData];
    
    // Do any additional setup after loading the view.
}
-(void)uiActivityindicatorviewStart
{
    self.alterView =[[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)] autorelease];
    self.alterView.backgroundColor =[UIColor whiteColor];
    self.HUD = [MBProgressHUD showHUDAddedTo:self.alterView animated:YES];
//    self.HUD.labelText = @"正在努力的给您加载";
    [self.HUD show:YES];
    
    [self.view addSubview:self.alterView];
    
}
-(void)uiActivityindicatorviewEnd
{
    [self.alterView removeFromSuperview];
}
#pragma mark - 创建集视图
- (void)creatCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    flowLayout.itemSize = CGSizeMake(WIDTHPRO * 170,HEIGHTPRO * 240);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(WIDTHPRO * 10 ,HEIGHTPRO * 10 , 0,HEIGHTPRO * 10);
#pragma mark - 根据TopView手动更改
    self.collectionView = [[[UICollectionView alloc] initWithFrame:CGRectMake(0,WIDTHPRO * 64, WIDTH, HEIGHT - HEIGHTPRO * 64) collectionViewLayout:flowLayout] autorelease];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.collectionView];
    
    
    [self.collectionView registerClass:[MXHomeContentCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [self uiActivityindicatorviewStart];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(uiActivityindicatorviewEnd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

/******************************** 数据解析部分 **********************************/
- (void)GetnineData
{
//================================ 9.9包邮数据 ===================================
    NSString *ninePath = @"http://api.nanyibang.com/campaign?campaignId=0&campaignType=9.9&hkm_sign=bf72ce4e52c2689b4e7fb1d560929fff&member_id=15243&member_type=member&page=1&random_key=24255&version=1.2.7";
    [AFNetworkHandler GETwithAFNByURL:ninePath completion:^(id result) {
//        NSLog(@"%@", result);
        NSDictionary *dataDict = [result objectForKey:@"data"];
        NSArray  *ItemDetailArr = [dataDict objectForKey:@"itemDetail"];
        for (NSDictionary *dict in ItemDetailArr) {
            MXHomeMailFreeModel *nineModel = [[[MXHomeMailFreeModel alloc] initWithDic:dict] autorelease];
            [self.nineArray addObject:nineModel];
        }
        [self.collectionView reloadData];
        [self uiActivityindicatorviewEnd];
    }];
    
}
- (void)GetnineTeenData
{
    //================================ 19.9包邮数据 ===================================
    NSString *ninePath = @"http://api.nanyibang.com/campaign?campaignId=0&campaignType=19.9&hkm_sign=bf72ce4e52c2689b4e7fb1d560929fff&member_id=15243&member_type=member&page=1&random_key=24255&version=1.2.7";
    [AFNetworkHandler GETwithAFNByURL:ninePath completion:^(id result) {
//        NSLog(@"%@", result);
        NSDictionary *dataDict = [result objectForKey:@"data"];
        NSArray  *ItemDetailArr = [dataDict objectForKey:@"itemDetail"];
        for (NSDictionary *dict in ItemDetailArr) {
            MXHomeMailFreeModel *nineModel = [[[MXHomeMailFreeModel alloc] initWithDic:dict] autorelease];
            [self.nineTeenArray addObject:nineModel];
        }
        [self.collectionView reloadData];
        [self uiActivityindicatorviewEnd];
    }];
    
}
- (void)GetTwentynineData
{
    //================================ 29.9包邮数据 ===================================
    NSString *ninePath = @"http://api.nanyibang.com/campaign?campaignId=0&campaignType=29.9&hkm_sign=bf72ce4e52c2689b4e7fb1d560929fff&member_id=15243&member_type=member&page=1&random_key=24255&version=1.2.7";
    [AFNetworkHandler GETwithAFNByURL:ninePath completion:^(id result) {
        NSDictionary *dataDict = [result objectForKey:@"data"];
        NSArray  *ItemDetailArr = [dataDict objectForKey:@"itemDetail"];
        for (NSDictionary *dict in ItemDetailArr) {
            MXHomeMailFreeModel *nineModel = [[[MXHomeMailFreeModel alloc] initWithDic:dict] autorelease];
            [self.twentynineArray addObject:nineModel];
        }
        [self.collectionView reloadData];
        [self uiActivityindicatorviewEnd];
    }];
    
}

#warning 尝试将数据解析方法放到 segment点击方法上面
- (void)segClick:(UISegmentedControl *)sender
{
    switch (sender.selectedSegmentIndex) {
        case 0:
            [self GetnineData];
            break;
        case 1:
            [self GetnineTeenData];
            break;
        case 2:
            [self GetTwentynineData];
            break;
            
        default:
            break;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - CollectionView 协议实现部分
/************************* CollectionView Delegate **************************/
//Collection中的组别个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个组别中元件的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.segmentControl.selectedSegmentIndex == 0) {
        return self.nineArray.count;
    } else if (self.segmentControl.selectedSegmentIndex == 1) {
        return self.nineTeenArray.count;
    }
    return self.twentynineArray.count;
}
//重用机制
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MXHomeContentCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor magentaColor];
    cell.layer.cornerRadius = 8;
    cell.layer.masksToBounds = YES;
    if (self.segmentControl.selectedSegmentIndex == 0) {
        
        [cell getmailFreeInfo:self.nineArray[indexPath.row]];
        
    } else if (self.segmentControl.selectedSegmentIndex == 1) {
        
        [cell getmailFreeInfo:self.nineTeenArray[indexPath.row]];
        
    } else {
        
        [cell getmailFreeInfo:self.twentynineArray[indexPath.row]];
        
    }
    return cell;
}
/*
//设置HeaderView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *topView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    [topView addSubview:self.topView];
    return topView;
}
*/

#pragma mark - 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MXHomeMailFreeItemDetailVC *detailVC = [[[MXHomeMailFreeItemDetailVC alloc] init] autorelease];
    if (self.segmentControl.selectedSegmentIndex == 0) {
        detailVC.mailFreeID = [self.nineArray[indexPath.row] _id];
    } else if (self.segmentControl.selectedSegmentIndex == 1) {
        detailVC.mailFreeID = [self.nineTeenArray[indexPath.row] _id];
    } else {
        detailVC.mailFreeID = [self.twentynineArray[indexPath.row] _id];
    }
    [self presentViewController:detailVC animated:YES completion:^{
    }];
}

- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
